package org.xqyy.eval.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import org.xqyy.eval.exception.SessionTimeoutException;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class SessionTimeoutInterceptor implements HandlerInterceptor {

    private List<String> allowUrls = new ArrayList<String>();
    public List<String> getAllowUrls() {
        return allowUrls;
    }
    public void setAllowUrls(List<String> allowUrls) {
        this.allowUrls = allowUrls;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String requestUrl = request.getRequestURI();
        for(String url : allowUrls) {
            if(requestUrl.endsWith(url)) {
                return true;
            }
        }
        if(WebUtils.getSessionAttribute(request, "user") == null) {
            throw new SessionTimeoutException("session超时");
        } else {
            return true;
        }
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {

    }
}
